package org.zhangkun.jmsg.webserver.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.zhangkun.jmsg.util.GlobalVar;
import org.zhangkun.jmsg.webserver.config.FileMemiConfig;
import org.zhangkun.jmsg.webserver.config.PageConfig;
import org.zhangkun.jmsg.webserver.config.ServletConfig;

public class WEBServer implements Runnable {


	private PageConfig pageConfig;

	private ServerSocket serverSocket;
	/**
	 * 
	 */
	private ServletConfig servlets;
	private FileMemiConfig staticRes;

	public static WEBServer instance = new WEBServer();

	public WEBServer() {
	}

	public PageConfig getConfig() {
		return pageConfig;
	}

	public ServletConfig getServlets() {
		return servlets;
	}

	public FileMemiConfig getStaticRes() {
		return staticRes;
	}

	public boolean init() throws IOException {
		try {
			servlets = new ServletConfig();
			if (!servlets.loadConfig(WEBServer.class
					.getResourceAsStream("/res/web/servlets.xml"))) {
				return false;
			}
			pageConfig = new PageConfig();
			if (!pageConfig.loadConfig(WEBServer.class
					.getResourceAsStream("/res/web/pageconfig.xml"))) {
				return false;
			}

			staticRes = new FileMemiConfig();
			if (!staticRes.loadConfig(WEBServer.class
					.getResourceAsStream("/res/web/files.xml"))) {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		serverSocket = new ServerSocket(GlobalVar.HTTP_PORT);
		new Thread(this, "WEBServer Thread").start();
		return true;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (true) {
			try {
				Socket socket = null;
				socket = serverSocket.accept();
				new DispatchSocket(this, socket).start();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				break;
			}
		}
	}

	public void setConfig(PageConfig config) {
		this.pageConfig = config;
	}

	public void setStaticRes(FileMemiConfig staticRes) {
		this.staticRes = staticRes;
	}

}
